#!/usr/bin/python
#Auther : MillionLee

'''
Do reg of MTPuGAE

maybe baseclass for other tools
'''

import cgi
import wsgiref.handlers
import Cookie

from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp

from getOAuth import GetOAuth
from userListCoushin import insertUser

from pageElements import *
from config import *

class DoReg(webapp.RequestHandler):
    def get(self):
        oAuther = GetOAuth()
        authUrl = oAuther.getAuthUrl(callback = MY_URL + "regmtpygaefinish");
       
        self.response.headers.add_header("Set-Cookie", "request_key=%s; " % oAuther.auth.request_token.key)
        self.response.headers.add_header("Set-Cookie", "request_secret=%s; " % oAuther.auth.request_token.secret)
        
        self.response.out.write(unicode((HEAD_REDIRECT % authUrl), 'gbk'))
        self.response.out.write(unicode((MTPYGAE_REG_REDIRECT % authUrl), 'gbk'))
        self.response.out.write(END)
#    def post(self):
#        self.redirect(GetOAuth().getAuthUrl(callback = MY_URL + "regmtpygaefinish"))
#        self.redirect('/regmtpygaefinish')

class FinishReg(webapp.RequestHandler):
    def get(self):
        try:
            request_token_key = self.request.cookies.get('request_key')
            request_token_secret = self.request.cookies.get('request_secret')
            oauth_verifier = self.request.get('oauth_verifier').strip()
            oAuther = GetOAuth()
            access_token = oAuther.getAccessToken(oauth_verifier, request_token_key, request_token_secret)
            insertUser(key = access_token.key, secret = access_token.secret, name = oAuther.getUsername())
        except Exception, e:
            self.response.out.write(e)
            return
        
        self.response.out.write(unicode(HEAD, 'gbk'))
        self.response.out.write(unicode(MTPYGAE_REG_OK, 'gbk'))
        self.response.out.write(END)
    
application = webapp.WSGIApplication([
  ('/regmtpygae', DoReg),
  ('/regmtpygaefinish', FinishReg)
], debug=False)

def main():
  wsgiref.handlers.CGIHandler().run(application)


if __name__ == '__main__':
  main()